import axios from "axios";
import { config } from "@/config/config";

const baseUrl: string = config.HTTP_URL;
const instance: any = axios.create({
  timeout: 5 * 1000,
  // @ts-ignore
  retry: 4,
  retryDelay: 500,
  baseURL: baseUrl
});
// 拦截器 -- 请求拦截
// @ts-ignore
instance.interceptors.request.use(config => {
  const token: string = localStorage["token"];
  const account: string = localStorage["account"];
  if (token) {
    config["headers"] = {
      "Authorization": `Bearer ${token} ${account}`
    };
  }
  return config;
//@ts-ignore
}, err => {
  return Promise.reject(err);
});
// 拦截器 -- 响应拦截
// @ts-ignore
instance.interceptors.response.use(res => {
  if (res.data.code == 400) {
    const errorMsg = {
      message: res.data.errMsg,
      duration: 2000
    };
    ElMessage.error(errorMsg);
    return;
  }
  return res;
  //@ts-ignore
}, err => {
  //出错重发4次间隔一秒
  const config = err.config;
  // If config does not exist or the retry option is not set, reject
  if (!config || !config.retry) return Promise.reject(err);
  
  // Set the variable for keeping track of the retry count
  config.__retryCount = config.__retryCount || 0;
  
  // Check if we've maxed out the total number of retries
  if (config.__retryCount >= config.retry) {
    // Reject with the error
    return Promise.reject(err);
  }
  // Increase the retry count
  config.__retryCount += 1;
  
  // Create new promise to handle exponential backoff
  const backoff = new Promise(function(resolve) {
    setTimeout(function() {
      resolve(true);
    }, config.retryDelay || 1);
  });
  
  // Return the promise in which recalls axios to retry the request
  return backoff.then(function() {
    return instance(config);
  });
});
export default instance;

